# -*- coding: utf-8 -*-
"""
Created on Thu Feb 14 18:18:07 2013

@author: Winand
"""
import cPickle as serial, socket, struct

#Exchange messages via self.request socket object
class SocketPipe(object):
    MSG_LEN_FIELD = 4
    def __init__(self, server=None, port=None, timeout=5):
        self.request = None #init var
        if server and port:
            self.connect(server, port, timeout)
        
    def connect(self, server, port, timeout=5): #create new connection
        req = socket.socket()
        req.settimeout(timeout)
        req.connect((server, port))
        req.settimeout(None)
        self.request = req
        
    def close(self): #close connection
        if self.request:
            self.request.close()
            self.request = None #reset var
        
    def __recv_bytes(self, ln):
        msg = ''
        while len(msg) != ln:
            chunk = self.request.recv(ln-len(msg))
            if chunk == '': raise RuntimeError("socket connection broken "+str(ln))
            msg = msg + chunk
        return msg
            
    def recv_data(self):
        msglen = struct.unpack('!i', self.__recv_bytes(self.MSG_LEN_FIELD))[0]
        return serial.loads(self.__recv_bytes(msglen))
        
    def send_data(self, var):
        dat = serial.dumps(var)
        self.request.sendall(struct.pack('!i', len(dat))+dat)
        
    def send(self, var): #wrapper
        self.send_data(var)
        return self.recv_data()
        